package cn.itcast.shiro;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

/**
 * 自定义的sessionManager
 */
public class CustomSessionManager extends DefaultWebSessionManager {

    /**
     * 头信息中具有sessionid
     *     请求头：Authorization： sessionid
     *
     * 指定sessionId的获取方式
     */
    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        //获取请求头Authorization中的数据
        String id = WebUtils.toHttp(request).getHeader("Authorization");
        if(StringUtils.isEmpty(id)){
            //如果没有携带，生成新的sessionId
            return super.getSessionId(request, response);
        }else{
            //返回sessionId；
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,"header");
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID,Boolean.TRUE);
            return id;
        }
    }

//<B>shiroSavedRequest</B>=org.apache.shiro.web.util.SavedRequest@5e4fc468<br>/n
//<B>org.apache.shiro.subject.support.DefaultSubjectContext_AUTHENTICATED_SESSION_KEY</B>=true<br>/n
//<B>org.apache.shiro.web.session.HttpServletSession.HOST_SESSION_KEY</B>=0:0:0:0:0:0:0:1<br>/n
//<B>org.apache.shiro.subject.support.DefaultSubjectContext_PRINCIPALS_SESSION_KEY</B>=cn.itcast.shiro.domain.User@6c494ade<br>/n
}
